#include "UserContext.h"

namespace tsc
{
namespace sgw
{

std::map<uint32_t, UserContext*> UserContext::msContextMap;

/*******************************************************************************
 *
 * Constructor
 *
 ******************************************************************************/
UserContext::UserContext(uint32_t clientId) :
	mUserClientId(clientId & 0x00FFFFFF),
	mpClientAddress(0),
	mClientUapPort(0),
	mNumOfGenerators(0)
{
	msContextMap.insert(
			std::pair<uint32_t, UserContext*>(mUserClientId, this));
} // UserContext::UserContext

/*******************************************************************************
 *
 * Destructor
 *
 ******************************************************************************/
UserContext::~UserContext()
{
	msContextMap.erase(this->mUserClientId);
	delete mpClientAddress;
}

bool
UserContext::findContext(uint32_t cliendId, UserContext*& context)
{
	std::map<uint32_t, UserContext*>::iterator it = msContextMap.find(cliendId);
	if(it != msContextMap.end())
	{
		context = it->second;
		return true;
	}
	return false;
}

uint32_t
UserContext::getUserClientId() const
{
	return mUserClientId;
}


ProtocolsCommon::IpAddress*
UserContext::getClientIpAddress() const
{
	return mpClientAddress;
}

void
UserContext::setClientIpAddress(ProtocolsCommon::IpAddress* ip)
{
    if(!mpClientAddress)
    {
        mpClientAddress = new ProtocolsCommon::IpAddress();
    }
	mpClientAddress->CopyFrom(*ip);
}

uint32_t
UserContext::getClientUapPort() const
{
	return mClientUapPort;
}

void
UserContext::setClientUapPort(uint32_t port)
{
	mClientUapPort = port;
}

void
UserContext::generatorCreated()
{
    mNumOfGenerators++;
}

void
UserContext::generatorRemoved()
{
    if(--mNumOfGenerators <= 0)
    {
        // last generator has been removed, delete context
        delete this;
    }
}

} // namespace sgw
} // namespace tsc
